package com.qh.servlet;

import com.qh.dao.Jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * com.qh.servlet
 * 26832
 * yjj
 * &#064;description: 登录业务
 * &#064;author: lxm
 * LoginServlet
 * &#064;create: 2024-06-06 20:52
 **/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username:"+username+" password:"+password);
        //登录数据
        String sql = "select * from users where urootname ='"+username+"' and pwd = '"+password+"'";
        Connection con = null;
        Statement smt = null;
        ResultSet rs = null;
        Jdbc jdbc = new Jdbc();
        List<User> list = new ArrayList<>();
        try{
            con = jdbc.getConnection();
            smt = con.createStatement();
            rs = smt.executeQuery(sql);
            while(rs.next()){
                User user = new User();
                user.setUsername(rs.getString("urootname"));
                user.setPassword(rs.getString("pwd"));
                user.setIdcard(rs.getString("idcard"));
                list.add(user);
            }
            if (!list.isEmpty()){
                HttpSession session = req.getSession();
                session.setAttribute("idcard",list.get(0).getIdcard());
                resp.getWriter().write("success");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                jdbc.close(con,smt,rs);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
